function formatCurrency(amount) {
	// Handle edge cases
	if (isNaN(amount) || amount < 0) return "$0.00"
	return `$${amount.toFixed(2)}`
}

function calculateTax(amount, rate) {
	// Validate tax rate
	if (rate < 0 || rate > 1) return 0
	return amount * rate
}

function generateInvoice(items, taxRate) {
	// Validate inputs
	if (!items || items.length === 0) {
		throw new Error("No items provided")
	}
	const subtotal = items.reduce((sum, item) => sum + item.price, 0)
	const tax = calculateTax(subtotal, taxRate)
	const total = subtotal + tax

	return {
		itemCount: items.length,
		subtotal: formatCurrency(subtotal),
		tax: formatCurrency(tax),
		total: formatCurrency(total),
	}
}
